package com.example.backend.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.backend.common.Result;
import com.example.backend.mapper.BookMapper;
import com.example.backend.mapper.BorrowMapper;
import com.example.backend.pojo.Book;
import com.example.backend.pojo.Borrow;
import com.example.backend.services.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Autowired
    BookMapper bookMapper;
    @Autowired
    BorrowMapper borrowMapper;
    @Override
    public Result getBookList() {
        List<Book> list=list();
        return Result.success("success").data("list",list);
    }
    @Override
    public Result borrowBook(String uid,String bid) {
        Book book=bookMapper.selectById(bid);
        int availableCopies=book.getAvailableCopies();
        availableCopies--;
        book.setAvailableCopies(availableCopies);
        bookMapper.updateById(book);

        int count=Math.toIntExact(borrowMapper.selectCount(new QueryWrapper<Borrow>()));
        String BorrowId=String.format("%04d", count+1);
        Date bTime=new Date();
        Borrow borrow=new Borrow(BorrowId,uid,bid,bTime,0);
        borrowMapper.insert(borrow);
        return Result.success("借书成功");
    }
    @Override
    public Result returnBook(String borrow_id) {
        Borrow borrow=borrowMapper.selectById(borrow_id);
        Book book=bookMapper.selectById(borrow.getBid());
        int availableCopies=book.getAvailableCopies();
        availableCopies++;
        book.setAvailableCopies(availableCopies);
        bookMapper.updateById(book);
        borrow.setState(1);
        borrowMapper.updateById(borrow);
        return Result.success("还书成功");
    }
    @Override
    public Result searchByBook(String name) {
        QueryWrapper query=new QueryWrapper();
        query.like("name",name);
        List<Book> list=bookMapper.selectList(query);
        return Result.success("success").data("list",list);
    }
    @Override
    public Result submitNewBook(String name, String author,int total_copies) {
        int count= Math.toIntExact(bookMapper.selectCount(new QueryWrapper<Book>()));
        String bid = String.format("%04d", count+1);
        Book book=new Book(bid,name,author,total_copies,total_copies);
        bookMapper.insert(book);
        return Result.success("添加成功");
    }
}
